package com.lanou.service.impl;

import com.lanou.entity.Commodity;
import com.lanou.entity.OrderData;
import com.lanou.entity.TbOrderItem;
import com.lanou.entity.TbOrderShipping;
import com.lanou.mapper.TbOrderShippingMapper;
import com.lanou.service.OrderService;
import com.lanou.utils.HttpClientUtils;
import com.lanou.utils.ShiHuiIDGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    TbOrderShippingMapper tbOrderShippingMapper;

    @Value("${CHECKED_CART_URL}")
    private String CHECKED_CART_URL;

    @Override
    public List<TbOrderShipping> findLocation(String id) {
        TbOrderShipping tbOrderShipping = tbOrderShippingMapper.selectByPrimaryKey(id);
        List<TbOrderShipping> list = new ArrayList<>();
        list.add(tbOrderShipping);
        return list;
    }

    @Override
    public OrderData createOrder(Long userId) {
        List<Commodity> commodities =
                HttpClientUtils.getList(CHECKED_CART_URL + "?userId=" + userId, Commodity.class);
        return parseOrderDataByCommodities(commodities, userId);
    }

    private OrderData parseOrderDataByCommodities(List<Commodity> commodities, Long userId) {
        OrderData orderData = new OrderData();
        // 订单ID的生成
        String orderId = ShiHuiIDGenerator.generateOrderID(userId);
        orderData.setOrderId(orderId);
        orderData.setUserId(userId);

        List<TbOrderItem> orderItems = new ArrayList<>();
        for (Commodity commodity : commodities) {
            TbOrderItem orderItem = parseCommodityToOrderItem(commodity, orderId);
            orderItems.add(orderItem);
        }
        orderData.setOrderItems(orderItems);
        return orderData;
    }

    private TbOrderItem parseCommodityToOrderItem(Commodity commodity, String orderId) {
        TbOrderItem orderItem = new TbOrderItem();
        orderItem.setItemId(commodity.getId().toString());
        orderItem.setNum(commodity.getAmount());
        orderItem.setOrderId(orderId);
        orderItem.setPicPath(commodity.getImg());
        orderItem.setPrice(commodity.getPrice());
        orderItem.setTitle(commodity.getTitle());
        orderItem.setTotalFee(commodity.getPrice() * commodity.getAmount());
        return orderItem;
    }
}
